package cn.sh.yhk.configure.scheduler;

/**
 * @Auther: adminyhk
 * @Date: 2018/9/21 14:32
 * @Description:
 */

import cn.sh.yhk.model.basic.STaskScheduleJob;
import cn.sh.yhk.service.basic.JobConfigService;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.List;

@Configuration
@EnableScheduling
public class SchedulerConfig {

    private static Logger log = LoggerFactory.getLogger(SchedulerConfig.class);
    @Autowired
    private JobConfigService jobConfigService;
    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public StdSchedulerFactory stdSchedulerFactory() {
        StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory();
        //获取JobConfig集合
        List<STaskScheduleJob> configs = jobConfigService.getAllByStatus(1);
        log.debug("Setting the Scheduler up");
        for (STaskScheduleJob config : configs) {
            try {
                Boolean flag = SchedulerUtil.createScheduler(config, applicationContext);
                System.out.println("执行结果：" + (flag == true ? "成功" : "失败"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return stdSchedulerFactory;
    }

    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(3);
        return taskScheduler;
    }

}
